<?php
/**
 * 退换货
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-06
 * Time: 17:44
 */

namespace App\Http\Controllers\Api\V1\Manager\Mall;


use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\Commodity;
use App\Models\CommoditySku;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderRefund;
use App\Models\OrderRefundLog;
use App\Models\User;
use App\Services\Front\UserScoreService;
use App\Services\Manager\RefundService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use League\Flysystem\Exception;

class RefundController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = $request->pageSize ? $request->pageSize : 20;
        $refundStatus = $request->refundStatus;
        $keyWords = $request->keyWords;
        $sql = OrderRefund::select('t3.totalPrice', 'refundId', 't1.orderNo', 't1.payType', 'applyTime', 'refundReason', 'refuseReason', 'refundStatus', 'refundPrice', 't1.userName', 't1.deliverName', 't1.deliverNo', 't1.deliverCode')
            ->from((new OrderRefund())->getTable() . ' as t1')
            ->leftJoin((new User())->getTable() . ' as t2', 't1.userId', '=', 't2.userId')
            ->join((new Order())->getTable() . ' as t3', 't3.orderNo', '=', 't1.orderNo');

        if ($refundStatus) {
            $sql->where('t1.refundStatus', $refundStatus);
        }
        if ($keyWords) {
            $sql->where('t1.orderNo', 'like', "%" . $keyWords . "%");
        }
        $data = $sql->orderBy('t1.refundId', 'desc')->paginate($pageSize)->toArray();
        $result['count'] = $data['total'];
        $result['refundList'] = $data['data'];
        return $this->apiResponse($result);
    }

    public function show($refundId)
    {
        $detail = OrderRefund::select('refundId', 'orderNo', 'payType', 'applyTime', 'refundReason', 'refuseReason', 'refundStatus', 'refundPrice','descPictures', 't1.userName', 'deliverName', 'deliverNo', 'deliverCode', 'skuId')
            ->from((new OrderRefund())->getTable() . ' as t1')
            ->join((new User())->getTable() . ' as t2', 't1.userId', '=', 't2.userId')
            ->where('refundId', $refundId)->first();
        if (!$detail) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $order = Order::where('orderNO', $detail['orderNo'])->first();
        $abc = new OrderController();
        $orderDetail = $abc->show($order['orderId'])->original['resultData'];
        $detail1 = $orderDetail['orderDetail'];
        foreach ($detail1 as $k => $v) {
            $refund = OrderRefund::where(['orderNo' => $v['orderNo'], 'skuId' => $v['skuId']])->first();
            $refundLog = OrderRefundLog::where('refundId', $refund['refundId'])->get()->toArray();

            if ($refund) {
                $detail1[$k]['refundStatus'] = $refund['refundStatus'];
                $detail1[$k]['refundId'] = $refund['refundId'];
                $detail1[$k]['refundLog'] = $refundLog;
            } else {
                $detail1[$k]['refundStatus'] = '';
            }
        }
        $orderDetail['orderDetail'] = $detail1;
        $deliver = app("kuaidi")->getData($detail['deliverCode'], $detail['deliverNo']);
        $result['detail'] = $detail;
        $result['orderDetail'] = $orderDetail;
        $result['deliver'] = $deliver;
        return $this->apiResponse($result);
    }

    public function refundRefuse(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'refundId' => 'integer|required',
            'refuseReason' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        try {
            \DB::beginTransaction();

            //改变退款表退款状态
            $status = OrderRefund::where(['refundId' => $data['refundId']])->update(['refuseReason' => $data['refuseReason'], 'refundStatus' => 'FAILED', 'finishTime' => date("Y-m-d H:i:s", time())]);
            if (!$status) {
                throw new \Exception("改变退款状态失败");
            }

            //获取退款订单号
            $refundDetail = OrderRefund::where(['refundId' => $data['refundId']])->first();
            if (!$refundDetail) {
                throw new \Exception("退款Id参数错误");
            }

            //判断存在不存在还有未审核的状态   失败的状态和待退款状态
            $status = OrderRefund::where(['orderNo' => $refundDetail['orderNo']])->whereNotIn('refundStatus', array('FAILED', 'WAITREFUND', 'SUCCEEDED'))->first();
            if (!$status) {//不存在，证明全部审核，处理订单表状态，若是全部退款，修改订单状态
                $refundService = new RefundService();
                //修改订单状态
                $refundService->updateOrder($refundDetail);
            }
            $abc = [];
            $abc['refundId'] = $data['refundId'];
            $abc['content'] = '拒绝退款';
            $abc['createTime'] = date('Y-m-d H:i:s');
            OrderRefundLog::create($abc);
            \DB::commit();
            return $this->apiResponse(true);
        } catch (\Exception $e) {
            \DB::rollback();
            \Log::error("RefundController refundRefuse" . $e->getMessage());
            return $this->apiResponse('', config('errorCode.REFUND_REFUSE_FAILED'));
        }
    }

    public function refundAgree($refundId)
    {
        $refundService = new RefundService();
        $flag = true;
        try {
            \DB::beginTransaction();

            //获取退款订单号
            $refundDetail = OrderRefund::where(['refundId' => $refundId])->first();
            if (!$refundDetail) {
                throw new \Exception("退款Id参数错误");
            }

            $status = Order::where(['orderNo' => $refundDetail['orderNo']])->first();
            if (!$status) {
                throw new \Exception("订单号错误");
            }
            $refundDetail['totalPrice'] = $status['totalPrice'];
            $refundDetail['payType'] = $status['payType'];

            // 通过订单判断退款订单应该返回到什么状态
            if ($status['deliverNo']) {//证明已经发货，需要管理员确认收货之后再退款
                $refundStatus = OrderRefund::where(['refundId' => $refundId, 'refundStatus' => 'PENDING'])->update(['refundStatus' => 'WAITRETURN']);


                if (!$refundStatus) {
                    throw new \Exception("改变退款状态失败");
                }
                $abc = [];
                $abc['refundId'] = $refundId;
                $abc['content'] = '等待买家邮寄商品';
                $abc['createTime'] = date('Y-m-d H:i:s');
                OrderRefundLog::create($abc);
                $flag = false; // 此状态不退款
            } else {//没有发货, 等待退款
                $orderDetail = OrderDetail::where('detailId', $refundDetail['orderDetailId'])->first();

                UserScoreService::decrementYangbeiByOrder($refundDetail['orderNo'], $refundDetail['userId'],$orderDetail['totalPrice']);
                UserScoreService::decrementScore($refundDetail['orderNo'], $refundDetail['userId'],$orderDetail['orderPrice']);

                $refundStatus = OrderRefund::where(['refundId' => $refundId, 'refundStatus' => 'PENDING'])->update(['refundStatus' => 'WAITREFUND']);

                if (!$refundStatus) {
                    throw new \Exception("改变退款状态失败");
                }
                 $orderDetail = OrderDetail::where(['orderNo' => $refundDetail['orderNo'], 'skuId' => $refundDetail['skuId']])->first();
                 if (!$orderDetail) {
                     throw new \Exception("获取订单详情失败");
                 }
                //增加库存
                $status = CommoditySku::where('skuId', $refundDetail['skuId'])->increment('stock', intval($orderDetail['amounts']));
                if (!$status) {
                    throw new \Exception("增加库存失败");
                }
                //减去销量
                $status = Commodity::where('commodityId', $refundDetail['commodityId'])->decrement('realSaleCount', intval($orderDetail['amounts']));

                if (!$status) {
                    throw new \Exception("减少销量失败");
                }
            }

            //判断存在不存在还有未审核的状态
            $refundOkStatus = OrderRefund::where(['orderNo' => $refundDetail['orderNo']])->whereNotIn('refundStatus', array('FAILED', 'WAITREFUND', 'SUCCEEDED'))->first();
            $refundFailed = OrderRefund::where(['orderNo' => $refundDetail['orderNo']])->where('refundStatus', 'FAILED')->first(); //等于失败
            $num = OrderDetail::where(['orderNo' => $refundDetail['orderNo']])->count();
            $num1 = OrderRefund::where(['orderNo' => $refundDetail['orderNo']])->count();
            if (!$refundOkStatus) {//不存在，证明全部审核，处理订单表状态，若是全部退款，修改订单状态
                if ($refundFailed) {//存在失败的状态，证明此订单要回滚到原来状态
                    //修改订单状态
                    $refundService->updateOrder($refundDetail);
                } else {
                    if ($num == $num1){//证明全部退款成功
                        $orderStatus = Order::where('orderNo', $refundDetail['orderNo'])->update(['orderStatus' => 'REFUNDEND']);
                        if (!$orderStatus) {
                            throw new \Exception("修改订单状态失败");
                        }
                    }

                }
                if ($flag) {
                    //开始退款
                    $refundService->onLineRefund($refundDetail, 1, $status['postage']);
                    $abc = [];
                    $abc['refundId'] = $refundId;
                    $abc['content'] = '退款完成';
                    $abc['createTime'] = date('Y-m-d H:i:s');
                    OrderRefundLog::create($abc);
                }

            } else {
                //开始退款
                if ($flag) {
                    $refundService->onLineRefund($refundDetail, 0);
                    $abc = [];
                    $abc['refundId'] = $refundId;
                    $abc['content'] = '退款完成';
                    $abc['createTime'] = date('Y-m-d H:i:s');
                    OrderRefundLog::create($abc);

                }

            }


            \DB::commit();
            return $this->apiResponse(true);
        } catch (\Exception $e) {
            \DB::rollback();
            \Log::error("RefundController refundRefuse" . $e->getMessage());
            return $this->apiResponse('', config('errorCode.REFUND_REFUSE_FAILED'));
        }


    }

    /**
     *  退货---确认到货  直接退款
     * @param $refundId
     * @return \Illuminate\Http\JsonResponse
     */
    public function refundDeliver($refundId)
    {
        $refundService = new RefundService();
        try {
            \DB::beginTransaction();

            //获取退款订单号
            $refundDetail = OrderRefund::where(['refundId' => $refundId])->first();
            if (!$refundDetail) {
                throw new \Exception("退款Id参数错误");
            }
            $orderDetail = OrderDetail::where('detailId', $refundDetail['orderDetailId'])->first();

            UserScoreService::decrementYangbeiByOrder($refundDetail['orderNo'], $refundDetail['userId'],$orderDetail['totalPrice']);
            UserScoreService::decrementScore($refundDetail['orderNo'], $refundDetail['userId'],$orderDetail['orderPrice']);
            $orderDetail = OrderDetail::where(['orderNo' => $refundDetail['orderNo'], 'skuId' => $refundDetail['skuId']])->first();
            if (!$orderDetail) {
                throw new \Exception("获取订单详情失败");
            }
            //增加库存
            $status = CommoditySku::where('skuId', $refundDetail['skuId'])->increment('stock', intval($orderDetail['amounts']));
            if (!$status) {
                throw new \Exception("增加库存失败");
            }
            //减去销量
            $status = Commodity::where('commodityId', $refundDetail['commodityId'])->increment('realSaleCount', intval($orderDetail['amounts']));

            if (!$status) {
                throw new \Exception("减少销量失败");
            }

            $refundStatus = OrderRefund::where(['refundId' => $refundId, 'refundStatus' => 'WAITCONFIRM'])->update(['refundStatus' => 'WAITREFUND']);
            if (!$refundStatus) {
                throw new \Exception("改变退款状态失败");
            }
            $abc['refundId'] = $refundId;
            $abc['content'] = '卖家已收货';
            $abc['createTime'] = date('Y-m-d H:i:s');
            OrderRefundLog::create($abc);
            //判断存在不存在还有未审核的状态
            $refundOkStatus = OrderRefund::where(['orderNo' => $refundDetail['orderNo']])->whereNotIn('refundStatus', array('FAILED', 'WAITREFUND', 'SUCCEEDED'))->first();
            $refundFailed = OrderRefund::where(['orderNo' => $refundDetail['orderNo']])->where('refundStatus', 'FAILED')->first(); //等于失败
            $num = OrderDetail::where(['orderNo' => $refundDetail['orderNo']])->count();
            $num1 = OrderRefund::where(['orderNo' => $refundDetail['orderNo']])->count();
            $status = Order::where(['orderNo' => $refundDetail['orderNo']])->first();
            $refundDetail['totalPrice'] = $status['totalPrice'];
            if (!$status) {
                throw new \Exception("订单号错误");
            }

            if (!$refundOkStatus) {//不存在，证明全部审核，处理订单表状态，若是全部退款，修改订单状态
                if ($refundFailed) {//存在失败的状态，证明此订单要回滚到原来状态
                    //修改订单状态
                    $refundService->updateOrder($refundDetail);
                } else {//证明全部退款成功
                    if ($num == $num1){//证明全部退款成功
                        $orderStatus = Order::where('orderNo', $refundDetail['orderNo'])->update(['orderStatus' => 'REFUNDEND']);
                        if (!$orderStatus) {
                            throw new \Exception("修改订单状态失败");
                        }
                    }
                }
                //开始退款
                $refundService->onLineRefund($refundDetail, 1, $status['postage']);
            } else {
                $refundService->onLineRefund($refundDetail);
            }
            \DB::commit();
            return $this->apiResponse(true);
        } catch (\Exception $e) {
            \DB::rollback();
            \Log::error("RefundController refundRefuse" . $e->getMessage());
            return $this->apiResponse('', config('errorCode.REFUND_REFUSE_FAILED'));
        }
    }
}
